#coding:utf8
from rest_framework import serializers
from .models import OAuthQQUser
from django_redis import get_redis_connection
from users.models import User


class QQTokenSerializer(serializers.Serializer):

    access_token = serializers.CharField(label='操作token')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[345789]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6)


    def validate(self, attrs):

        #判断短信验证码是否正确
        sms_code = attrs.get('sms_code')
        mobile = attrs.get('mobile')
        redis_conn = get_redis_connection('code')
        redis_code = redis_conn.get('sms_%s'%mobile)
        if redis_code is None:
            raise serializers.ValidationError('短信验证码过期')
        if redis_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码不一致')

        #判断token
        token = attrs.get('access_token')
        openid = OAuthQQUser.check_user_token(token)
        if openid is None:
            raise serializers.ValidationError('绑定验证码失效')
        #将openid放置到 attr中备用
        attrs['openid'] = openid

        #判断手机号是否被注册
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user = None
        else:
            #判断用户的密码是否正确
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError('密码错误')
            attrs['user'] = user


        return attrs

    #数据入库
    def create(self, validated_data):

        user = validated_data.get('user')

        if user is None:
            user = User.objects.create(
                username = validated_data['username'],
                password = validated_data['password'],
                mobile = validated_data['mobile']
            )
            user.set_password(validated_data['password'])

        qquser = OAuthQQUser.objects.create(
            user = user,
            openid = validated_data['openid']
        )

        return user
